package com.yoo.chat.kit.conversation;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.google.gson.JsonObject;

import com.yoo.chat.kit.IMCenter;
import com.yoo.chat.kit.http.APIRequest;
import com.yoo.chat.kit.model.ActionModel;
import com.yoo.chat.kit.activity.RongBaseActivity;
import com.yoo.chat.kit.event.EnumEventTag;
import com.yoo.chat.kit.model.TypingInfo;
import com.yoo.chat.kit.userinfo.RongUserInfoManager;
import com.yoo.chat.kit.userinfo.model.GroupUserInfo;
import com.yoo.chat.kit.utils.RouteUtils;
import com.yoo.module_base.utils.SaveDeviceUtil;
import com.yoo.ons.R;
import com.yoo.ons.ToastUtil;
import com.yoo.ons.base.HttpRequestListener;
import com.yoo.ons.dialog.ProfileInfoBannerDialogFragment;
import com.yoo.ons.dialog.UserActionPopup;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;

import java.util.HashMap;
import java.util.Locale;

public class RongConversationActivity extends RongBaseActivity {
    protected String mTargetId;
    protected Conversation.ConversationType mConversationType;
    protected ConversationFragment mConversationFragment;
    private ConversationViewModel conversationViewModel;
    private boolean flashClick = false;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        initData();
        setContentView(R.layout.rc_conversation_activity);
        setTitle();
        Bundle bundle = getIntent().getExtras();
        mConversationFragment =
                (ConversationFragment)
                        getSupportFragmentManager().findFragmentById(R.id.conversation);
        newTitleBar.setMoreVisible(!SaveDeviceUtil.Companion.getServiceUserCode().equals(mTargetId));
        mTitleBar.setVisibility(View.GONE);
        initListener();
        initViewModel();
        observeUserInfoChange();
        newTitleBar.setTitleCLickListener(new Function0<Unit>() {
            @Override
            public Unit invoke() {
                //点击标题显示信息弹窗
                ProfileInfoBannerDialogFragment.Companion.newInstance(mTargetId,3).show(getSupportFragmentManager());
                return null;
            }
        });
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            mTargetId = intent.getStringExtra(RouteUtils.TARGET_ID);
            String type = intent.getStringExtra(RouteUtils.CONVERSATION_TYPE);
            if (!TextUtils.isEmpty(type)) {
                mConversationType =
                        Conversation.ConversationType.valueOf(type.toUpperCase(Locale.US));
            } else {
                return;
            }
        }
    }

    @Override
    public boolean isShowNewTitleBar() {
        return true;
    }

    private void initListener() {
//        newTitleBar.getIvBack().setOnClickListener(view -> {
//            if (mConversationFragment != null
//                    && !mConversationFragment.onBackPressed()) {
//                finish();
//            }
//        });
//        newTitleBar.getIvMore().setOnClickListener(view -> {
//            if (mConversationFragment != null) {
//                mConversationFragment.onOtherClick();
//            }
//        });
//        newTitleBar.getTvUserName().setOnClickListener(view -> {
//            if (mConversationFragment != null) {
//                mConversationFragment.onTitleClick();
//            }
//        });
    }

    private void observeUserInfoChange() {
        if (!TextUtils.isEmpty(mTargetId)) {
            RongUserInfoManager.getInstance().addUserDataObserver(mUserDataObserver);
        }
    }

    private final RongUserInfoManager.UserDataObserver mUserDataObserver =
            new RongUserInfoManager.UserDataObserver() {
                @Override
                public void onUserUpdate(UserInfo info) {
                    if (TextUtils.equals(mTargetId, info.getUserId())) {
                        runOnUiThread(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        setTitle();
                                    }
                                });
                    }
                }

                @Override
                public void onGroupUpdate(Group group) {
                    if (TextUtils.equals(mTargetId, group.getId())) {
                        runOnUiThread(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        setTitle();
                                    }
                                });
                    }
                }

                @Override
                public void onGroupUserInfoUpdate(GroupUserInfo groupUserInfo) {
                    // do nothing
                }
            };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!TextUtils.isEmpty(mTargetId)) {
            RongUserInfoManager.getInstance().removeUserDataObserver(mUserDataObserver);
//            if (flashClick) {
//                SDEventManager.post(true, EnumEventTag.INDEX_LIKE_SWIPED.ordinal());
//            }
        }
    }

    private void setTitle() {
//        if (!TextUtils.isEmpty(mTargetId)
//                && mConversationType.equals(Conversation.ConversationType.GROUP)) {
//            Group group = RongUserInfoManager.getInstance().getGroupInfo(mTargetId);
//            mTitleBar.setTitle(group == null ? mTargetId : group.getName());
//        } else {
//            UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(mTargetId);
//            mTitleBar.setTitle(userInfo == null ? mTargetId : userInfo.getName());
//        }
        //只显示Name，不显示TargetId
        UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(mTargetId);
        if (!TextUtils.isEmpty(mTargetId)
                && mConversationType.equals(Conversation.ConversationType.GROUP)) {
            Group group = RongUserInfoManager.getInstance().getGroupInfo(mTargetId);
            newTitleBar.setTitleText(group == null ? "" : group.getName());
        } else {
            newTitleBar.setTitleText(userInfo == null ? "" : userInfo.getName());
        }
        newTitleBar.setTitleBarBackground(com.yoo.module_res.R.drawable.shape_chat_title_bg);
        newTitleBar.setMoreVisible(true);
        newTitleBar.setMoreListener(() -> {
            new UserActionPopup(this,mTargetId,new UserActionPopup.UserActionListener(){

                @Override
                public void userBlack() {
                    addAction(1,"",mTargetId);

                }

                @Override
                public void userReport(@NonNull String reason) {
                    addAction(4,reason,mTargetId);

                }
            }).showPopupWindow();

            return null;
        });
//        if (!TextUtils.isEmpty(userInfo.getExtra())){
//            newTitleBar.getTvSubTitle().setText(userInfo.getExtra());
//        }
//        if (userInfo!=null && userInfo.getPortraitUri() != null) {
//            Glide.with(this)
//                    .load(userInfo.getPortraitUri())
//                    .into(newTitleBar.getTvUserImg());
//        }
        if (mConversationType.equals(Conversation.ConversationType.CUSTOMER_SERVICE)
                || mConversationType.equals(Conversation.ConversationType.CHATROOM)) {
//            mTitleBar.setRightVisible(false);
        }
    }

    private void addAction(int opType,String reason,String userCodeFriend){
        APIRequest.INSTANCE.addAction(new HttpRequestListener<ActionModel>() {
            @Override
            public void addRequestParams(@NonNull HashMap<String, Object> params) {
                params.put("opType",opType);
                if (!reason.equals("")){
                    params.put("reason",reason);
                }
                params.put("userCodeFriend",userCodeFriend);
            }

            @Override
            public void success(@Nullable ActionModel s) {
                if (opType== 1){
                    ToastUtil.INSTANCE.showToast(getString(com.yoo.module_res.R.string.black_toast));
                    IMCenter.getInstance().removeConversation(
                            Conversation.ConversationType.PRIVATE,
                            mTargetId,
                            new RongIMClient.ResultCallback<Boolean>() {
                                        @Override
                                        public void onSuccess(Boolean aBoolean) {
                                            new Handler().postDelayed(new Runnable() {
                                                @Override
                                                public void run() {
                                                    finish();
                                                }
                                            }, 200);
                                        }

                                        @Override
                                        public void onError(RongIMClient.ErrorCode e) {
                                        }
                                    });
                }else{
                    ToastUtil.INSTANCE.showToast(getString(com.yoo.module_res.R.string.report_toast));
                }
            }
        });
    }


    private void initViewModel() {
        conversationViewModel = new ViewModelProvider(this).get(ConversationViewModel.class);
        conversationViewModel
                .getTypingStatusInfo()
                .observe(
                        this,
                        new Observer<TypingInfo>() {
                            @Override
                            public void onChanged(TypingInfo typingInfo) {
                                if (typingInfo == null) {
                                    return;
                                }
                                if (typingInfo.conversationType == mConversationType
                                        && mTargetId.equals(typingInfo.targetId)) {
                                    if (typingInfo.typingList == null) {
                                        mTitleBar.getMiddleView().setVisibility(View.VISIBLE);
                                        mTitleBar.getTypingView().setVisibility(View.GONE);
                                    } else {
                                        mTitleBar.getMiddleView().setVisibility(View.GONE);
                                        mTitleBar.getTypingView().setVisibility(View.VISIBLE);
                                        TypingInfo.TypingUserInfo typing =
                                                typingInfo.typingList.get(
                                                        typingInfo.typingList.size() - 1);
                                        if (typing.type == TypingInfo.TypingUserInfo.Type.text) {
                                            mTitleBar.setTyping(
                                                    com.yoo.module_res.R.string.rc_conversation_remote_side_is_typing);
                                        } else if (typing.type
                                                == TypingInfo.TypingUserInfo.Type.voice) {
                                            mTitleBar.setTyping(
                                                    com.yoo.module_res.R.string.rc_conversation_remote_side_speaking);
                                        }
                                    }
                                }
                            }
                        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
            if (mConversationFragment != null && !mConversationFragment.onBackPressed()) {
                finish();
            }
        }
        return false;
    }
}
